angular.module('planIndex', ['toastr', 'common'])
    .controller('planIndexController',
        ['$scope', '$http', 'toastr', 'commonService',
            function ($scope, $http, toastr) {
                var role = $("#myRole").val();
                var page = 0;
                var size = 10;
                var displayType = "project";
                var mapping = null;
                var teamDetail = null;
                $scope.thisPage = false;
                $scope.groupProject = null;
                $scope.groupManager = null;
                $scope.plan = {
                    id: $("#pl_id").val(),
                    pl_name: $("#pl_name").val(),
                    start_date: new Date($("#start").val()).Format("yyyy/MM/dd"),
                    end_date: new Date($("#end").val()).Format("yyyy/MM/dd"),
                    next_plan: $("#next").val()
                };

                if (!!$.cookie("toast")) {
                    toastr.success($.cookie("toast"));
                    $.cookie("toast", "");
                }

                $http.post("/plan/find", {limit: page * size, count: (page + 1) * size}).success(function (rows) {
                    buildList(rows);
                    if (!$scope.thisPage) {
                        $scope.nextPage("loop");
                    }
                });

                $scope.findGroup = function (type) {
                    if (!mapping) {
                        $http.get("/user/mapping", {}).success(function (data) {
                            mapping = data;
                            mapping.p_status.inactive = "<span style='color: red'>已删除</span>";
                            mapping.project = {};
                            $http.post('/project/findAll', {all: true}).success(function (data) {
                                data.forEach(function (e) {
                                    mapping.project[e.p_id] = e.p_name;
                                });
                            });
                            callback();
                        });
                    } else {
                        callback();
                    }
                    function callback() {
                        var totals = 0;
                        displayType = type;
                        if (!$scope.groupProject) {
                            $scope.groupProject = {};
                            $http.post("/plan/detail/findGroup", {
                                type: "project",
                                plan_id: $scope.plan.id
                            }).success(function (rows) {
                                for (var i = 0; i < rows.length; i++) {
                                    totals += rows[i].percentage;
                                    rows[i].status = mapping.p_status[rows[i].status];
                                    rows[i].project_pm = mapping.name[rows[i].project_pm];
                                    rows[i].project_leader = mapping.name[rows[i].project_leader];
                                    rows[i].fk_usr = mapping.name[rows[i].fk_usr];
                                    if (i == 0 || rows[i - 1].p_id != rows[i].p_id) {
                                        $scope.groupProject[rows[i].p_id] = rows[i];
                                    }
                                    !$scope.groupProject[rows[i].p_id].detail && ($scope.groupProject[rows[i].p_id].detail = []);
                                    !$scope.groupProject[rows[i].p_id].total && ($scope.groupProject[rows[i].p_id].total = 0.0);
                                    $scope.groupProject[rows[i].p_id].display = true;
                                    $scope.groupProject[rows[i].p_id].detail.push({
                                        contribute: rows[i].percentage * 100,
                                        user: rows[i].fk_usr
                                    });
                                    $scope.groupProject[rows[i].p_id].total += rows[i].percentage;
                                    type == "project" ? buildView(type) : 'else build manager view';
                                }
                                $("#totals").text(totals.toFixed(2));
                            });
                        } else {
                            type == "project" ? buildView(type) : 'else build manager view';
                        }
                        if (!$scope.groupManager) {
                            $scope.groupManager = {};
                            $http.post("/plan/detail/findGroup", {
                                type: "manager",
                                plan_id: $scope.plan.id
                            }).success(function (rows) {
                                for (var i = 0; i < rows.length; i++) {
                                    if (i == 0 || rows[i - 1].leader != rows[i].leader) {
                                        $scope.groupManager[rows[i].leader] = rows[i];
                                    }
                                    !$scope.groupManager[rows[i].leader].detail && ($scope.groupManager[rows[i].leader].detail = []);
                                    !$scope.groupManager[rows[i].leader].total && ($scope.groupManager[rows[i].leader].total = 0.0);

                                    $scope.groupManager[rows[i].leader].display = true;
                                    $scope.groupManager[rows[i].leader].detail.push({
                                        contribute: rows[i].percentage * 100,
                                        user: rows[i].fk_usr,
                                        project: rows[i].fk_prj
                                    });
                                    $scope.groupManager[rows[i].leader].total += rows[i].percentage;
                                }
                                type == "manager" ? buildView(type) : 'else build project view';
                            });
                        } else {
                            type == "manager" ? buildView(type) : 'else build project view';
                        }
                    }
                };

                $scope.searchList = function () {
                    var query = {limit: page * size, count: (page + 1) * size};
                    if ($("#start_date").val()) {
                        query.start_date = $("#start_date").val();
                    }
                    if ($("#end_date").val()) {
                        query.end_date = $("#end_date").val();
                    }
                    $http.post("/plan/find", query).success(function (data) {
                        buildList(data);
                    }).error(function () {
                        toastr.error("请检查网络连接");
                    });
                };

                $scope.nextPage = function (loop) {
                    var query = {limit: (page + 1) * size, count: (page + 2) * size};
                    if ($("#start_date").val()) {
                        query.start_date = $("#start_date").val();
                    }
                    if ($("#end_date").val()) {
                        query.end_date = $("#end_date").val();
                    }
                    $http.post("/plan/find", query).success(function (data) {
                        if (data.data.length == 0) {
                            toastr.warning("已经是最后一页");
                        } else {
                            page++;
                            buildList(data);
                            if (!$scope.thisPage && !!loop) {
                                $scope.nextPage("loop");
                            }
                        }
                    }).error(function () {
                        toastr.error("请检查网络连接");
                    });
                };

                $scope.previousPage = function () {
                    if (page == 0) {
                        toastr.warning("已经是第一页");
                    } else {
                        var query = {limit: (page - 1) * size, count: (page) * size};
                        if ($("#start_date").val()) {
                            query.start_date = $("#start_date").val();
                        }
                        if ($("#end_date").val()) {
                            query.end_date = $("#end_date").val();
                        }
                        $http.post("/plan/find", query).success(function (data) {
                            page--;
                            buildList(data);
                        }).error(function () {
                            toastr.error("请检查网络连接");
                        });
                    }
                };

                $scope.savePlan = function () {
                    if ($scope.plan.pl_name.trim().length == 0) {
                        toastr.warning("请输入计划名称");
                        return;
                    }
                    if ($scope.plan.start_date > $scope.plan.end_date) {
                        toastr.warning("开始时间不得大于结束时间");
                        return;
                    }
                    $http.post("/plan/edit", $scope.plan).success(function (data) {
                        if (data == "success") {
                            window.location.href = window.location.href;
                            $.cookie("toast", "保存成功");
                        } else {
                            toastr.error("保存失败！" + data.description);
                        }
                    }).error(function () {
                        toastr.error("请检查网络连接");
                    });
                };

                window.showTab = function (leader) {
                    if (!teamDetail) {
                        teamDetail = {};
                        $http.post('/member/find', {role: ["member", "intern"]}).success(function (data) {
                            data.forEach(function (e) {
                                if (e.manager) {
                                    !teamDetail[e.manager] && (teamDetail[e.manager] = []);
                                    teamDetail[e.manager].push(e.u_id);
                                }
                            });
                            refreshPanel();
                        });
                    } else {
                        refreshPanel();
                    }

                    function refreshPanel() {
                        var html = "";
                        var displayData = $scope.groupManager[leader];
                        $(".tab-item.active").removeClass("active");
                        $("#tab-item-" + leader).addClass("active");
                        $(".team-detail").remove();

                        html += '<div class="team-detail col-md-12 kick-padding-margin" style="display: none">';
                        html += '<ul class="col-md-4 list-group">\
                            <li class="list-group-item" style="background-color: #2a6496;color:#bbb">' + displayData.t_name + '</li>\
                            <li class="list-group-item list-group-item-info" style="background-color: #6AF">\
                            <i class="fa fa-user"></i>组长:' + mapping.name[leader] + '</li>';
                        teamDetail[leader] && teamDetail[leader].forEach(function (e) {
                            html += '<li class="list-group-item list-group-item-info">' + mapping.name[e] + '</li>';
                        });
                        html += '</ul><ul class="col-md-8 list-group kick-padding-margin">\
                            <li class="list-group-item" style="background-color: #2a6496;color:#bbb">\
                            <div class="col-md-3">项目</div>\
                            <div class="col-md-9">投入百分比</div></li>';
                        var projectGroup = {};
                        for (var i = 0; i < displayData.detail.length; i++) {
                            if (i == 0 || displayData.detail[i].project != displayData.detail[i - 1].project) {
                                projectGroup[displayData.detail[i].project] = [];
                            }
                            projectGroup[displayData.detail[i].project].push(displayData.detail[i]);
                        }
                        for (var i in projectGroup) {
                            html += '<li class="list-group-item list-group-item-info">\
                                <div class="col-md-3 kick-padding-margin">' + mapping.project[i] + '</div>\
                                <div class="col-md-9 kick-padding-margin">';
                            projectGroup[i].forEach(function (e) {
                                html += '<div class="col-md-4 manager-view-detail"><div class="col-md-7 kick-padding-margin">' + mapping.name[e.user] + ':</div>' +
                                    '<div class="col-md-5 kick-padding-margin" style="color: red;padding-right: 25px;">'+ e.contribute + '%</div></div>';
                            });
                            html += '</div></li>';
                        }
                        html += '</ul></div>';
                        $("#manager-view").append(html);
                        $(".team-detail").show(300);
                    }
                };

                function buildList(rows) {
                    if (!rows.data || rows.data.length == 0) {
                        toastr.warning("未搜索到结果");
                        return;
                    }
                    var html = "";
                    for (var i = 0; i < rows.data.length; i++) {
                        var active = "";
                        if (rows.data[i].pl_id == $scope.plan.id) {
                            active = "active";
                            $scope.thisPage = true;
                        }
                        if (rows.data[i].status == 'latest') {
                            html += '<div class="list-group-item p-list hand ' + active + '" onclick="javascript:window.location.href=\'/plan/find?plan_id=' + rows.data[i].pl_id + '\'">' +
                                '<div class="col-md-10" style="color: darkred;">' +
                                '&nbsp;<i style="font-size: 4px;position: relative;top:-5px;">new&nbsp;</i><i class="fa fa-calendar-o"></i>&nbsp;&nbsp;' + rows.data[i].pl_name + '</div>' +
                                '<a class="col-md-2 fa fa-file-excel-o" style="padding-top: 3px;cursor: pointer" ' +
                                'target="_blank" href="/plan/export/' + rows.data[i].pl_id + '"></a></div>';
                        } else {
                            html += '<div class="list-group-item p-list hand ' + active + '" onclick="javascript:window.location.href=\'/plan/find?plan_id=' + rows.data[i].pl_id + '\'">' +
                                '<div class="col-md-10">' + rows.data[i].pl_name + '</div>' +
                                '<a class="col-md-2 fa fa-file-excel-o" style="padding-top: 3px;cursor: pointer" ' +
                                'target="_blank" href="/plan/export/' + rows.data[i].pl_id + '"></a></div>';
                        }
                    }

                    $(".p-list").each(function () {
                        $(this).remove();
                    });
                    $("#allPlans").append(html);
                }

                function buildView(type) {
                    var html = "";
                    if (type == 'project') {
                        $("#manager-view").hide(300);
                        $("#project-view").show(300);

                        for (var i in $scope.groupProject) {
                            if ($scope.groupProject[i].display) {
                                html += '<li onclick="expand(' + $scope.groupProject[i].p_id + ')" class="list-by-project list-group-item list-group-item-info">\
                                <div class="col-md-2">' + $scope.groupProject[i].p_name + '</div>\
                                <div class="col-md-3">' + $scope.groupProject[i].project_pm + '/' +
                                    $scope.groupProject[i].project_leader + '</div>\
                                <div class="col-md-2">' + $scope.groupProject[i].status + '</div>\
                                <div class="col-md-3">' + new Date($scope.groupProject[i].start_date).Format("yyyy-MM-dd") + '~' +
                                    new Date($scope.groupProject[i].end_date).Format("yyyy-MM-dd") + '</div>\
                                <div class="col-md-1">' + $scope.groupProject[i].total.toFixed(2) + '</div>\
                                <div class="col-md-1 fa fa-angle-double-up" style="padding-top: 3px;" id="expand-' +
                                    $scope.groupProject[i].p_id + '"></div>\
                                </li>';

                                var detailArray = $scope.groupProject[i].detail;
                                if (detailArray.length == 1) {
                                    html += '<li style="list-style: none;display: none" class="list-by-project list-toggle" id="prj-' +
                                        $scope.groupProject[i].p_id + '">\
                                    <ul class="list-group list-no-border">\
                                    <li class="list-group-item list-group-item-warning">\
                                    <div class="col-md-2"></div>\
                                    <div class="col-md-3">开发人员</div>\
                                    <div class="col-md-2">投入百分比</div>\
                                    </li>\
                                    <li class="list-group-item">\
                                    <div class="col-md-2 fa fa-angle-right"></div>\
                                    <div class="col-md-3"><span>' + detailArray[0].user + '</span></div>\
                                    <div class="col-md-2">' + detailArray[0].contribute + '%</div>\
                                    </li></ul></li>';
                                } else {

                                    html += '<li style="list-style: none;display: none" class="list-by-project list-toggle" id="prj-' +
                                        $scope.groupProject[i].p_id + '">\
                                    <ul class="list-group list-no-border">\
                                    <li class="list-group-item list-group-item-warning">\
                                    <div class="col-md-2"></div>\
                                    <div class="col-md-3">开发人员</div>\
                                    <div class="col-md-2" style="border-right: 1px solid #3af">投入百分比</div>\
                                    <div class="col-md-3">开发人员</div>\
                                    <div class="col-md-2">投入百分比</div>\
                                    </li>';
                                    for (var j = 0; j < detailArray.length; j += 2) {
                                        html += '<li class="list-group-item">\
                                            <div class="col-md-2 fa fa-angle-right"></div>\
                                            <div class="col-md-3"><span>' + detailArray[j].user + '</span></div>\
                                            <div class="col-md-2" style="border-right: 1px solid #666">' +
                                            detailArray[j].contribute + '%</div>';
                                        if (detailArray[j + 1]) {
                                            html += '<div class="col-md-3"><span>' + detailArray[j + 1].user + '</span></div>\
                                            <div class="col-md-2">' + detailArray[j + 1].contribute + '%</div>'
                                        }
                                    }
                                    html += '</li></ul></li>';
                                }
                            }
                            $(".list-by-project").each(function () {
                                $(this).remove();
                            });
                            $("#project-view ul").append(html);
                        }
                    } else {
                        $("#manager-view").show(300);
                        $("#project-view").hide(300);
                        $(".tab-item").remove();
                        var first;
                        for (var i in $scope.groupManager) {
                            !first && (first = i);
                            if ($scope.groupManager[i].display) {
                                $(".team-tab").append('<li class="tab-item" id="tab-item-' + i + '"><a onclick="showTab(' + i + ')">' +
                                    mapping.name[$scope.groupManager[i].leader] + '</a></li>')
                            }
                        }
                        window.showTab(first);
                    }
                }

                (function initDate() {
                    if (role == 'admin') {
                        $("#start").datetimepicker({
                            format: 'Y/m/d',
                            timepicker: false,
                            onClose: function () {
                                $scope.plan.start_date = $("#start").val();
                            }
                        });
                        $("#end").datetimepicker({
                            format: 'Y/m/d',
                            timepicker: false,
                            onClose: function () {
                                $scope.plan.end_date = $("#end").val();
                            }
                        });
                    }
                    $("#start_date").datetimepicker({
                        format: 'Y-m-d',
                        timepicker: false
                    });
                    $("#end_date").datetimepicker({
                        format: 'Y-m-d',
                        timepicker: false
                    });
                })();
                $scope.findGroup('project');
            }

        ]);